<?php
// 应用公共文件
use app\common\model\RuinuoApp;
use app\common\model\RuinuoMode;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\View;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Request;
use think\facade\Cache;
use app\common\model\AdminUser;
use app\common\model\RuinuoSetting;
use app\common\model\AdminOptions;

!defined('DS') && define('DS', DIRECTORY_SEPARATOR);
/*返回状态码
200=成功
201=未登录
202=没有权限
203=表单验证失败
500=服务器错误
*/
if (!function_exists('BackCode')) {

    function BackCode($data = [], $code = 200, $msg = "Success")
    {
        $rs = [
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'time' => date('Y-m-d H:i:s')
        ];
        return json($rs);
    }
}

/*生成Token*/
if (!function_exists('signToken')) {
    function signToken($arr, $time = 86400)
    {
        $key = GetConfig('system', 'system_jwt');
        $payload = array(
            "iss" => '',
            "aud" => '',
            "iat" => time(),
            "nbf" => time(),
            "exp" => time() + $time,
            "data" => $arr
        );
        $jwt = JWT::encode($payload, $key, 'HS256');
        return $jwt;
    }
}

/*验证Token*/
if (!function_exists('checkToken')) {
    function checkToken($token = '')
    {
        $key = GetConfig('system', 'system_jwt');
        $status = array("code" => 201);
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
            $arr = (array)$decoded;
            $res['code'] = 200;
            $ddata = json_encode($arr['data']);
            $ddata = json_decode($ddata, true);
            $res['data'] = $ddata;
            return $res;

        } catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
            $status['msg'] = "签名不正确";
            return $status;
        } catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
            $status['msg'] = "token未生效";
            return $status;
        } catch (\Firebase\JWT\ExpiredException $e) { // token过期
            $status['msg'] = "token已过期";
            return $status;
        } catch (Exception $e) { //其他错误
            $status['msg'] = "token错误";
            return $status;
        }
    }
}


/*获取token值*/
if (!function_exists('GetToken')) {
    function GetToken($field = '')
    {
        $token = Request::header('token') ?: Cookie::get('token');
        if (empty($token)) {
            return "";
        }
        $res = checkToken($token);
        if (empty($res['data'][$field])) {
            return "";
        }
        return $res['data'][$field];
    }
}

/*生成文件*/
if (!function_exists('getCreatetxt')) {

    function getCreatetxt($path, $txt)
    {
        if (file_exists($path)) {
            $str = file_get_contents($path);
            if (strpos($str, '自定义页面') !== false) {
                return true;
            }
        }
        @$file = fopen($path, 'w');
        $bo = false;
        if ($file) {
            $bo = true;
            if ($txt) $bo = fwrite($file, $txt);
            fclose($file);
        }
        return $bo;
    }
}


/*
删除文件夹
*/
if (!function_exists('GetDelDir')) {
    function GetDelDir($dir = "")
    {
        if (!file_exists($dir)) {
            return false;
        }
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    @unlink($fullpath);
                } else {
                    GetDelDir($fullpath);
                }
            }
        }
        closedir($dh);
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }

}
/*
删除文件
*/
if (!function_exists('GetDelDirfile')) {
    function GetDelDirfile($dir = "")
    {
        if (file_exists($dir)) {
            @unlink($dir);
        }
    }
}


/*加密文件*/
if (!function_exists('getBase64encode')) {
    function getBase64encode($str = '')
    {
        if ($str == '') return '';
        $str = base64_encode($str);
        $str = str_replace(array('+', '/', '='), array('!', '.', ':'), $str);
        return $str;
    }
}

/*解密文件*/
if (!function_exists('getBase64decode')) {
    function getBase64decode($str = '')
    {
        if ($str == '') return '';
        $str = str_replace(array('!', '.', ':'), array('+', '/', '='), $str);
        $str = base64_decode($str);
        return $str;
    }
}

if (!function_exists('t')) {
    function t()
    {
        $t['key'] = getBase64decode(GetConfig('system', 'shop_key'));
        $t['api'] = getBase64decode(GetConfig('system', 'shop_url'));
        return $t;
    }
}
/*下划线转驼峰*/
if (!function_exists('GetCamelize')) {
    function GetCamelize($name = '', $separator = '_')
    {
        $name = $separator . str_replace($separator, " ", strtolower($name));
        return ltrim(str_replace(" ", "", ucwords($name)), $separator);
    }
}

/*后台模板路径*/
if (!function_exists('ViewTpl')) {
    function ViewTpl($tpl = '')
    {
        $view_path = App()->getRootPath() . "/app/common/template" . DIRECTORY_SEPARATOR;
        View::config(['view_path' => $view_path]);
        $tpl = str_replace(".html", "", $tpl);
        return View::fetch($tpl);
    }
}
/*系统配置
group_num=配置分组
field=字段名称
*/
if (!function_exists('GetConfig')) {

    function GetConfig($code, $field)
    {
        $CacheId = 'ruinuo_setting_code_' . $code;
        if (Cache::get($CacheId)) {
            $data = Cache::get($CacheId);
        } else {
            $RuinuoSetting = new RuinuoSetting();
            $setting = $RuinuoSetting->where("num='" . $code . "'")->field('values')->find();
            $data = !empty($setting['values']) ? json_decode($setting['values'], true) : [];
            Cache::set($CacheId, $data, 600);
        }
        return !empty($data[$field]) ? $data[$field] : '';
    }
}

/*转树形*/
if (!function_exists('GetTree')) {
    function GetTree($items = [], $field = '', $child_field = '', $parent_id = 0)
    {
        $lists = [];
        foreach ($items as $item) {
            if ($item[$field] === $parent_id) {
                $child = GetTree($items, $field, $child_field, $item['id']);
                if (!empty($child)) {
                    $item[$child_field] = $child;
                }
                $lists[] = $item;
            }
        }
        return $lists;
    }
}


/*获取数据源
num=编码
*/
if (!function_exists('GetOptions')) {
    function GetOptions($num = '', $post = [])
    {
        $back = [];
        $nums = explode('|', $num);
        $options = AdminOptions::where("num='" . $nums[0] . "'")->field("config,type,url,label,value,url,is_token,mode_id")->find();
        $type = !empty($options['type']) ? $options['type'] : 1;
        $CacheId = 'ruinuo_options_' . $nums[0];
        if (Cache::get($CacheId)) {
            $data['rows'] = Cache::get($CacheId);
        }
        if ($type == 3) {
            $RuinuoMode = new RuinuoMode();
            $Mode= $RuinuoMode->where("id='" . $options['mode_id'] . "'")->field('app_id,num')->find();
            if (!empty($Mode))
            {
                $RuinuoApp = new RuinuoApp();
                $App=$RuinuoApp->where("id='" . $Mode['app_id'] . "'")->field("num")->find();
                $options['url']='/'.$App['num'].'/'.$Mode['num'].'/lists/';
                $options['is_token']=1;
            }
        }
        switch ($type) {
            case 2:
            case 3:
                $pdata = [];
                $url = GetUrl() . $options['url'];
                if (count($nums) >= 2) {
                    foreach ($nums as $k => $v) {
                        if ($k >= 1) {
                            $pdata[$v] = !empty($post[$v]) ? $post[$v] : '';
                        }
                    }
                }
                $headers = [];
                if ($options['is_token'] == 1) {
                    $token = Request::header('token') ?: Cookie::get('token');
                    $headers = array(
                        'Content-Type: application/json;charset=UTF-8',
                        'token:' . $token
                    );
                }
                $item = json_decode(GetHttp($url, $pdata, 'POST', $headers), true);
                $item = !empty($item['data']['rows']) ? $item['data']['rows'] : [];
                $item = OptionsChildren($item, $options['label'], $options['value']);
                foreach ($item as $k => $v) {
                    $back[] = $v;
                }
                break;
            default:
                $config = !empty($options['config']) ? json_decode($options['config'], true) : [];
                foreach ($config as $kk => $vv) {
                    $back[] = [
                        'label' => $vv['label'],
                        'value' => $vv['value'],
                    ];
                }
        }
        Cache::set($CacheId, $back, 600);
        $data['rows'] = $back;
        return $data;
    }
}
if (!function_exists('OptionsChildren')) {
    function OptionsChildren($arr, $label, $value)
    {
        $back = [];
        $labelarr = explode(',', $label);
        foreach ($arr as $k => $v) {
            $label_val = '';
            foreach ($labelarr as $kk => $vv) {
                $val = !empty($v[$vv]) ? $v[$vv] : '';
                if ($kk >= 1) {
                    $val = '-' . $val;
                }
                $label_val .= $val;
            }
            $back[$k] = [
                'label' => $label_val,
                'value' => !empty($v[$value]) ? $v[$value] : '',
            ];
            if (!empty($v['children'])) {
                $back[$k]['children'] = OptionsChildren($v['children'], $label, $value);
            }
        }
        return $back;
    }
}

if (!function_exists('GetUrl')) {
    function GetUrl()
    {
        $url = (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
        $server_name = $url . $_SERVER['HTTP_HOST'];
        return $server_name;
    }
}

/*获取后台用户资料*/
if (!function_exists('GetAdminUser')) {

    function GetAdminUser($uid, $name = 'name')
    {
        $AdminUser = new AdminUser();
        $CacheId = 'ruinuo_user_' . $uid;
        if (Cache::get($CacheId)) {
            $user = Cache::get($CacheId);
        } else {
            $user = $AdminUser->where("id='" . $uid . "'")->find();
            Cache::set($CacheId, $user, 600);
        }
        return !empty($user[$name]) ? $user[$name] : '';
    }
}


/**
 * 发送HTTP请求方法，目前只支持CURL发送请求
 * @param string $url 请求URL
 * @param array $params 请求参数
 * @param string $method 请求方法GET/POST
 * @return array $data  响应数据
 */
if (!function_exists('GetHttp')) {

    function GetHttp($url = '', $params = [], $method = 'GET', $header = array(), $multi = false)
    {
        $opts = [
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => $header
        ];
        switch (strtoupper($method)) {
            case 'GET' :
                if (!empty($params)) {
                    $url = $url . '&' . http_build_query($params);
                }
                $opts[CURLOPT_URL] = $url;
                break;
            case 'POST' :
                $params = $multi ? $params : http_build_query($params);
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
        }
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        return $data;
    }
}





